﻿var zombies = zombies || {};
var windowURL = window.URL || window.webkitURL;

zombies.PointList = function () {
    var self = this;
    self.Pages = ko.observableArray();
    self.Loaded = ko.observable(false);
    self.MemPoints = ko.observableArray();
    self.CurrentPage = ko.observable();
    self.Avatar = ko.observable("../Advertise/DefaultAssets/NoAvatar.gif");
    self.FullName = ko.observable();

    self.ChangePage = function (page) {
        self.MemPoints.removeAll();

        $.ajax({
            url: '/api/MemberProfile/GetPointList/' + page,
            type: 'GET',
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        }).done(function (request) {
            self.Pages.removeAll();
            for (i = 1; i <= request.totalPage && request.totalPage > 1; i++) {
                self.Pages.push(i);
            }
            $.each(request.list, function (idx, item) {
                self.MemPoints.push(new zombies.MemPoint(item));
            });
        }).fail(function (request) {
            self.Loaded(false);
        });
    }
};

zombies.MemPoint = function (item) {
    var self = this;
    self.No = item.No;
    self.TimeView = moment(item.TimeView).format('LLL');
    self.Title = item.Title;
    self.Point = item.Point;
    self.AdvId = item.AdvId;
};

var load = function (cur){

    $.ajax({
        type: "GET",
        url: "/api/MemberProfile/GetUserProfile",
        contentType: "application/json",
        dataType: 'json'
    }).done(function (item) {
        if (item.Avatar != null && item.Avatar != '') {
            pointListViewModel.Avatar(item.Avatar);
        }
        pointListViewModel.FullName(item.FirstName + ' ' + item.LastName);
        pointListViewModel.Loaded(true);
    });

    if (pointListViewModel.Loaded) {
        pointListViewModel.CurrentPage(cur);
        pointListViewModel.MemPoints.removeAll();

        $.ajax({
            url: '/api/MemberProfile/GetPointList/' + cur,
            type: 'GET',
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        }).done(function (request) {
            for (i = 1; i <= request.totalPage && request.totalPage > 1; i++) {
                pointListViewModel.Pages.push(i);
            }
            $.each(request.list, function (idx, item) {
                pointListViewModel.MemPoints.push(new zombies.MemPoint(item));
            });
        }).fail(function (request) {
            pointListViewModel.Loaded(false);
        });
    }
};

var pointListViewModel;
$(document).ready(function () {
    pointListViewModel = new zombies.PointList();
    load(1);
    ko.applyBindings(pointListViewModel, document.getElementById("my-container"));
});